﻿using MyOCR_WPF.Tool;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using RestSharp;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace MyOCR_WPF.OCRHelper
{
    public class BaiduOCR : IOCR
    {
        // 百度云中开通对应服务应用的 API Key 建议开通应用的时候多选服务
        private static String clientId;
        // 百度云中开通对应服务应用的 Secret Key
        private static String clientSecret;
        public BaiduOCR()
        {
            clientId = ConfigurationManager.AppSettings["Baidu_OCR_Id"];
            clientSecret = ConfigurationManager.AppSettings["Baidu_OCR_Key"];
        }

        private String getAccessToken()
        {
            String authHost = "https://aip.baidubce.com/oauth/2.0/token";
            RestClient client = new RestClient(authHost);
            RestRequest request = new RestRequest(Method.POST);
            request.AddParameter("grant_type", "client_credentials");
            request.AddParameter("client_id", clientId);
            request.AddParameter("client_secret", clientSecret);

            var result = client.Execute(request);
            Console.WriteLine(result.Content);
            JObject jObject = (JObject)Newtonsoft.Json.JsonConvert.DeserializeObject(result.Content);
            String access_token = jObject["access_token"].ToString();
            return access_token;
        }

        public string SendImg(Bitmap img)
        {
            string token = getAccessToken();
            RestClient restclient = new RestClient("https://aip.baidubce.com/rest/2.0/ocr/v1/general_basic");
            RestRequest request = new RestRequest(Method.POST);
            request.AddParameter("access_token", token);
            request.AddParameter("image", ImageProcessing.ImageToBase64(img));
            request.AddParameter("language_type", "CHN_ENG");
            var result = restclient.Execute(request);
            dynamic json = JsonConvert.DeserializeObject(result.Content);
            var lst = new List<string>();
            foreach (var item in json.words_result)
            {
                lst.Add(item.words.ToString());
            }
            return string.Join("", lst);
        }
    }
}
